package com.weighing.system.utils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class SerialNumberUtil {

    /**
     * 生成当前时间流水号（格式：yyyyMMddHHmmss）
     * @return 时间流水号字符串
     */
    public static String generateSerialNumber(String prefix) {
        SimpleDateFormat sdf = new SimpleDateFormat(prefix);
        return sdf.format(new Date());
    }

    /**
     * 生成yyyyMMddHHmmss的Long值 减去八小时
     * return  Long
     */
    public static Long generateSerialNumberLongSub8() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime dateTime = LocalDateTime.now().minusHours(8); // 减去8小时
        return Long.parseLong(dateTime.format(formatter));
    }

    /**
     * 还原时间戳
     * @param recentlyCuXlTime 减去8小时后的yyyyMMddHHmmss时间信息
     * @return 时间戳
     */
    public static Long restoreOriginalTimestamp(Long recentlyCuXlTime) {
        if (recentlyCuXlTime == null) {
            return null;
        }
        if (recentlyCuXlTime <= 0) {
            return recentlyCuXlTime;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 解析为 LocalDateTime
        LocalDateTime time = LocalDateTime.parse(String.valueOf(recentlyCuXlTime), formatter);

        // 转成中国时区的 ZonedDateTime
        ZonedDateTime zdt = time.atZone(ZoneId.of("Asia/Shanghai"));

        // 转成毫秒时间戳
        return zdt.toInstant().toEpochMilli();
    }


    // 测试
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // parse 字符串为 LocalDateTime
        LocalDateTime adjustedTime = LocalDateTime.parse("20251127174332", formatter);

        // 加 8 小时
        LocalDateTime originalTime = adjustedTime.plusHours(8);

        // 输出结果
        System.out.println(originalTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

}
